package com.caiyi.financial.nirvana.sms.service;


import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.entity.SmsUserRecharge;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserRechargeTypeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsUserMapper;
import com.caiyi.financial.nirvana.sms.querybean.PageBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryUserBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryUserProductBean;
import com.caiyi.financial.nirvana.sms.querybean.UserRechargeQueryBean;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import com.caiyi.financial.nirvana.sms.vo.SmsUserProductListVo;
import com.github.pagehelper.PageHelper;
import com.youyu.common.utils.YyAssert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class SmsUserService extends BaseService<SmsUser> {

    private static final AtomicLong ORDERNUMSEED = new AtomicLong();
    public static final ThreadLocal<SimpleDateFormat> YYMMDDHHMMSS = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyMMddHHmmss");
        }
    };

    @Autowired
    private SmsUserMapper smsUserMapper;

    private static String random() {
        String body = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
        String result = "";
        Random rd = new Random();
        for (int i = 0; i < 6; i++) {
            int intVal = rd.nextInt(62);
            System.out.println(intVal);
            result = result + body.charAt(intVal) + "";
        }
        return result;
    }

    public int addUser(SmsUser smsUser) {
        YyAssert.isFalse(isExistAccount(smsUser), ReturnCodeEnum.FAILED.code, "账号/扩展码已经存在");
        String password = smsUser.getPassword();
        if (StringUtils.isBlank(password)) {
            smsUser.setPassword(random());
        }
        int insertCount = this.insertByEntitySelective(smsUser);
        SmsUser user = selectByAccount(smsUser.getAccount());
        //redis中添加用户
        String key = String.format(JedisKey.SMS_USER, user.getAccount());
        JedisService.set(key, JSON.toJSONString(user));
        key = String.format(JedisKey.SMS_BALANCE, user.getAccount());
        JedisService.set(key, "0");
        key = String.format(JedisKey.SMS_EXTEND_ACCOUNT, user.getExtendCode());
        JedisService.set(key, user.getAccount());
        return insertCount;
    }


    public int deleteUser(Integer id) {
        SmsUser smsUser = new SmsUser();
        smsUser.setId(id);
        smsUser = this.selectByPrimaryKey(smsUser);
        int deleteCount = this.deleteByPrimaryKey(smsUser);
        //redis中删除User,balance,extendCode队列
        String key = String.format(JedisKey.SMS_USER, smsUser.getAccount());
        JedisService.del(key);
        key = String.format(JedisKey.SMS_BALANCE, smsUser.getAccount());
        JedisService.del(key);
        key = String.format(JedisKey.SMS_EXTEND_ACCOUNT, smsUser.getExtendCode());
        JedisService.del(key);
        return deleteCount;
    }

    @Transactional
    public int addSmsNum(SmsUserRecharge userRecharge) {
        int type = userRecharge.getType();
        int value = userRecharge.getSmsNum();
        if (type == SmsUserRechargeTypeEnum.REFUND.index) {
            value = -value;
        }
        int updateCount = smsUserMapper.addSmsNum(value, userRecharge.getId());
        Integer afterNum = value + userRecharge.getBeforeNum();
        userRecharge.setAfterNum(afterNum);
        Date createTime = new Date();
        userRecharge.setCreateTime(createTime);
        userRecharge.setUpdateTime(createTime);
        userRecharge.setOrderNum(generateOrderNum());
        smsUserMapper.insertUserRecharge(userRecharge);
        //更新redis余额队列
        String key = String.format(JedisKey.SMS_BALANCE, userRecharge.getAccount());
        JedisService.set(key, afterNum.toString());
        return updateCount;
    }

    public int updateStatus(Integer id) {
        SmsUser smsUser = new SmsUser();
        smsUser.setId(id);
        int updateCount = smsUserMapper.changeStatus(id);
        //redis中修改user的status
        smsUser = this.selectByPrimaryKey(smsUser);
        Integer status = smsUser.getStatus();
        String key = String.format(JedisKey.SMS_USER, smsUser.getAccount());
        if (status == SmsUserStatusEnum.ENABLE.index) {
            //状态为1，在redis中添加user
            JedisService.set(key, JSON.toJSONString(smsUser));
        } else {
            //状态为2，在redis中删除user
            JedisService.del(key);
        }
        return updateCount;
    }

    public int updatePassword(Integer id) {
        SmsUser smsUser = new SmsUser();
        smsUser.setId(id);
        int updateCount = smsUserMapper.updatePassword(random(), id);
        //redis中修改user的password
        smsUser = this.selectByPrimaryKey(smsUser);
        String key = String.format(JedisKey.SMS_USER, smsUser.getAccount());
        JedisService.set(key, JSON.toJSONString(smsUser));
        return updateCount;
    }

    public int updateUser(SmsUser smsUser) {
        YyAssert.isFalse(isExistAccount(smsUser), ReturnCodeEnum.FAILED.code, "扩展码已经存在");
        int updateCount = this.updateByEntitySelective(smsUser);
        //判断User状态
        smsUser = selectByPrimaryKey(smsUser);
        int status = smsUser.getStatus();
        //状态为启用时更新redis
        if (status == SmsUserStatusEnum.ENABLE.index) {
            //redis中更新User,extendCode队列
            String key = String.format(JedisKey.SMS_USER, smsUser.getAccount());
            String oldUserStr = JedisService.get(key);
            if (StringUtils.isNotBlank(oldUserStr)) {
                SmsUser oldUser = JSON.parseObject(oldUserStr, SmsUser.class);
                String oldKey = String.format(JedisKey.SMS_EXTEND_ACCOUNT, oldUser.getExtendCode());
                JedisService.del(oldKey);
            }
            JedisService.set(key, JSON.toJSONString(smsUser));
            key = String.format(JedisKey.SMS_EXTEND_ACCOUNT, smsUser.getExtendCode());
            JedisService.set(key, smsUser.getAccount());
        }
        return updateCount;
    }

    public PageBean<SmsUser> getUserList(QueryUserBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsUser> list = smsUserMapper.selectUserList(bean);
        PageBean<SmsUser> pageBean = new PageBean<>(list);
        return pageBean;
    }


    public PageBean<SmsUserProductListVo> getProductListByParams(QueryUserProductBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsUserProductListVo> list = smsUserMapper.selectProductListByParams(bean);
        PageBean<SmsUserProductListVo> pageBean = new PageBean<SmsUserProductListVo>(list);
        return pageBean;
    }

    public PageBean<SmsUserRecharge> getUserRechargeListByParams(UserRechargeQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsUserRecharge> list = smsUserMapper.selectUserRechargeListByParams(bean);
        PageBean<SmsUserRecharge> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public boolean isExistAccount(SmsUser smsUser) {
        int count = smsUserMapper.isExistAccount(smsUser);
        if (count > 0) {
            return true;
        }
        return false;
    }

    public String showPassword(Integer id) {
        return smsUserMapper.selectPassword(id);
    }

    public List<String> getAccountList() {
        return smsUserMapper.selectAllAccount();
    }

    /**
     * 根据账户名获取短信账户
     *
     * @param loginAccount 账户名
     * @return SmsUser
     */
    public SmsUser selectByAccount(String loginAccount) {
        return smsUserMapper.selectByAccount(loginAccount);
    }

    /**
     * 获取用户中最大的扩展码
     *
     * @return
     */
    public int getMaxExtendCode() {
        try {
            String extendCode = smsUserMapper.getMaxExtendCode();
            if (StringUtils.isNotBlank(extendCode)) {
                return Integer.parseInt(extendCode);
            }
        } catch (Exception e) {
            logger.error("get getMaxExtendCode error...", e);
        }
        return 0;
    }

    /**
     * 充值单号自增
     */
    public static final String generateOrderNum() {
        long orderNumSeed = ORDERNUMSEED.incrementAndGet();
        if (orderNumSeed >= 9000) {
            orderNumSeed = orderNumSeed % 9000;
        }
        orderNumSeed += 1000;
        SimpleDateFormat df = YYMMDDHHMMSS.get();
        return df.format(new Date()) + orderNumSeed;
    }

    /**
     * 查询数据库中所有账号
     *
     * @return
     */
    public List<String> selectAccountList() {
        return smsUserMapper.selectAccountList();
    }
}
